package com.yy.QSManage.api;

import com.yy.QSManage.common.Result;
import com.yy.QSManage.model.entity.FaSysRoleMenu;
import com.yy.QSManage.model.validatio.Update;
import com.yy.QSManage.service.FaSysRoleMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/FaSysRoleMenuApi")
@Api(tags = "角色关联菜单权限")
public class FaSysRoleMenuApi extends BaseApi<FaSysRoleMenu>{

    @Autowired
    FaSysRoleMenuService roleMenuService;

    @ApiOperation("获取角色权限")
    @ApiImplicitParam(name = "roleId", value = "权限id", required = true, dataType = "String", paramType = "path")
    @GetMapping("/rolePower/{roleId}")
    public Result<List<FaSysRoleMenu>> rolePower(@PathVariable String roleId){
        return Result.success(baseService.listByParam(FaSysRoleMenu::getRoleId, roleId));
    }

    @ApiOperation("权限设置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleMenus", value = "查询参数", required = true, dataType = "List", paramType = "body"),
            @ApiImplicitParam(name = "roleId", value = "权限id", required = true, dataType = "String", paramType = "path")
    })
    @PostMapping("/powerSet/{roleId}")
    public Result<Boolean> powerSet(@RequestBody @Validated(Update.class) List<FaSysRoleMenu> roleMenus, @PathVariable String roleId){
        // 查询原有权限
        List<FaSysRoleMenu> oldRoleMenus = roleMenuService.listByParam(FaSysRoleMenu::getRoleId, roleId);
        // 新增
        List<FaSysRoleMenu> addRoleMenus = new ArrayList<>();
        // 编辑
        List<FaSysRoleMenu> editRoleMenus = new ArrayList<>();
        for (FaSysRoleMenu roleMenu : roleMenus) {
            // 判断是否存在该角色该菜单配置
            List<FaSysRoleMenu> collect = oldRoleMenus.stream().filter(item -> item.getMenuId().equals(roleMenu.getMenuId())).collect(Collectors.toList());
            // 新增
            if(collect.isEmpty()){
                addRoleMenus.add(roleMenu);
            }else{
                FaSysRoleMenu oldRoleMenu = collect.get(0);
                // 移除存在元素，不删除
                oldRoleMenus.remove(oldRoleMenu);
                //编辑
                oldRoleMenu.setFunctionRole(roleMenu.getFunctionRole());
                editRoleMenus.add(oldRoleMenu);
            }
        }
        roleMenuService.saveBatch(addRoleMenus);
        roleMenuService.updateBatchById(editRoleMenus);
        roleMenuService.removeByIds(oldRoleMenus);
        return Result.success();
    }
}

